package com.thon.controller.system;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thon.alipay.util.MD5Util;
import com.thon.commons.utils.ApplicationEnum.UserStatus;
import com.thon.controller.util.BaseController;
import com.thon.dao.util.Page;
import com.thon.entity.user.User;
import com.thon.security.AuthcType;
import com.thon.security.CaptchaUsernamePasswordToken;
import com.thon.service.message.TextMessageService;
import com.thon.service.user.UserService;
import com.thon.service.user.UserSettingService;

/**
 * @file RegistController.java
 * @author thon
 * @email thon.ju@gmail.com
 * @date Aug 16, 2013 9:55:46 AM
 * @description 用户注册相关控制器
 */
@Controller
@RequestMapping(value = "/regist")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class RegistController extends BaseController {
	private static final Log log = LogFactory.getLog(RegistController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private UserSettingService userSettingService;
	@Autowired
	private TextMessageService textMessageService;

	@RequestMapping(method = RequestMethod.GET)
	public String register() {
		return "regist";
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String webRegist(HttpServletRequest request, Model model) {
		
		String phone = request.getParameter("loginName");
		
		String password = request.getParameter("plainPassword");
		String name = request.getParameter("name");
		String tmp = request.getParameter("code");
		HttpSession session = request.getSession();
		String code = (String) session.getAttribute(phone);
		Page<User> page = new Page<User>();
		page = userService.findUserByName(page, name);
		if(code.equals(tmp) ) {
			User user = new User();
			user.setStatus(UserStatus.open.getCode());
			user.setLoginName(phone);
			user.setPlainPassword(password);
			user.setName(name);
		//	user.setRoles("user");
			user.setFund(0);
			log.debug("userId"+user.getId());
			userService.registUser(user);	
			String authcType = AuthcType.REGIST;
			CaptchaUsernamePasswordToken token = new CaptchaUsernamePasswordToken(phone, password, true,"","",authcType);
			
	        Subject u = SecurityUtils.getSubject();	       
	            u.login(token);
			return "index";
		}
		return "regist";
	}

	/*
	 * 移动端注册用户接口
	 * 返回一个User 实体
	 */
	@RequestMapping(value = "/rest",method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> regist(@Valid @RequestBody User user, Model model) {

		user.setStatus(UserStatus.open.getCode());
		//user.setRoles("user");
		user.setFund(0);
		userService.registUser(user);
		return new ResponseEntity(HttpStatus.CREATED);
	}
	
	//生成并发送手机6位激活码
	@RequestMapping(value = "/text/send", method = RequestMethod.POST)
	public ResponseEntity<?> registSend(HttpServletRequest request) throws IOException { 
		
		Map<String, Object> map = Maps.newHashMap();
		HttpSession session = request.getSession();
		String phone = request.getParameter("username");
		String text = String.valueOf(Math.random()).substring(2,8);
		String value = "#code#="+text;
		session.setAttribute(phone, text);
		String res = textMessageService.tplSendSms(value, phone, TextMessageService.SEND_VERIFICATION_CODE);
		map.put("msg", res);
		return new ResponseEntity(map, HttpStatus.OK);
	}
	
	//移动端生成发送验证码
	@RequestMapping(value = "/text/send", method = RequestMethod.GET)
	public ResponseEntity<?> registSendMobile(@RequestParam(value = "loginName", required = true)String loginName) throws IOException { 
		
		Map<String, Object> map = Maps.newHashMap();
		String text = String.valueOf(Math.random()).substring(2,8);
		String value = "#code#="+text;
		String res = textMessageService.tplSendSms(value, loginName, TextMessageService.SEND_VERIFICATION_CODE);
		text = MD5Util.MD5(text);//MD5加密
		map.put("code", text);
		return new ResponseEntity(map, HttpStatus.OK);
		
	}
	
	//确认验证码并激活帐号
	@RequestMapping(value = "/active", method = RequestMethod.POST)
	@ResponseBody
	public Boolean registerActive(HttpServletRequest request){
		
		String phone = request.getParameter("username");
		String tmp = request.getParameter("code");
		HttpSession session = request.getSession();
		String code = (String) session.getAttribute(phone);
		if( tmp.equals(code) ) {
			User user = userService.getUserByEmail(phone);
			user.setStatus(UserStatus.open.getCode());
					
			return true;
		}
		else {
			return false;
		}
	}
	

//	@RequestMapping(value = "/active/{code}", method = RequestMethod.GET)
//	public String registerActive(@PathVariable("code") String code, Model model)
//			throws IOException {
//
//		@SuppressWarnings("deprecation")
//		String activeCode = IOUtils.toString(Encodes.decodeBase64(code));
//		String[] strings = StringUtils.split(activeCode, "&");
//		String phone = strings[0];
//		String time = strings[1];
//
//		if (StringUtils.isBlank(phone) || StringUtils.isBlank(time)) {
//			model.addAttribute("error",
//					"Illegal request.Please copy from phone again. ");
//		}
//		Date nowDate = new Date();
//		Date requestDate = new Date(Long.valueOf(time));
//
//		log.debug("active phone : " + phone);
//		log.debug("active time : " + requestDate);
//
//		if (nowDate.compareTo(requestDate) > 0) {
//			model.addAttribute("error",
//					"This link is outdate.Please regist again, then active. ");
//		}
//
//		User user = userService.getUser(phone, null);
//		if (user != null
//				&& StringUtils.equals(user.getStatus(),
//						UserStatus.locked.getCode())) {
//			user.setStatus(UserStatus.open.getCode());
//			userService.updateUser(user);
//			model.addAttribute("success", "Active success.");
//		} else if (user != null
//				&& StringUtils.equals(user.getStatus(),
//						UserStatus.open.getCode())) {
//			model.addAttribute("success",
//					"This account has been actived already.");
//		} else if (user != null
//				&& StringUtils.equals(user.getStatus(),
//						UserStatus.expired.getCode())) {
//			model.addAttribute("error",
//					"This account is outdate.Please regist again, then active. ");
//		}
//
//		return "regist-active";
//	}

	/**
	 * Ajax请求校验loginName是否唯一。
	 */
	@RequestMapping(value = "/check_login_name")
	@ResponseBody
	public Boolean checkLoginName(@RequestParam("loginName") String loginName) {
		if (userService.getUser(loginName, null) == null) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 *  验证昵称是否唯一。
	 */
	@RequestMapping(value = "/check_name")
	@ResponseBody
	public Boolean checkName(@RequestParam("name") String name){
		Page<User> page = new Page<User>();
		page = userService.findUserByName(page, name);
		if(page.getResult().size()==0){
			return true;
		}else{
			return false;
		}
	}
	
}
